package jpavlich.cardsorter;

import java.awt.geom.Point2D;

import jpavlich.cardsorter.action.SerializableLocation;

import fr.inria.zvtm.engine.Camera;
import fr.inria.zvtm.engine.Location;
import fr.inria.zvtm.engine.View;
import fr.inria.zvtm.glyphs.Glyph;
import fr.inria.zvtm.glyphs.RectangularShape;
import fr.inria.zvtm.glyphs.VText;

public class Util {

	public static SerializableLocation calculateDestination(Glyph g, float mFactor, View view,
			Camera camera){
		// Code adapted from ZVTM's View class
	    if (camera.getOwningView() != view){return null;}
	    double x;
	    double y;
	    if (g instanceof VText){
	        VText t=(VText)g;
	        Point2D.Double p = t.getBounds(camera.getIndex());
	        if (t.getTextAnchor()==VText.TEXT_ANCHOR_START){
	            x=g.vx+p.x/2; //-camera.vx;
	            y=g.vy+p.y/2; //-camera.vy;
	        }
	        else if (t.getTextAnchor()==VText.TEXT_ANCHOR_MIDDLE){
	            x=g.vx; //-camera.vx;
	            y=g.vy; //-camera.vy;
	        }
	        else {
	            x=g.vx-p.x/2; //-camera.vx;
	            y=g.vy-p.y/2; //-camera.vy;
	        }
	    }
	    else {
	        x=g.vx; //-camera.vx;
	        y=g.vy; //-camera.vy;
	    }
	        double newAlt = 0;
	        // compute the new altitude to see glyph g entirely horizontally
	        if (view.getPanel().getComponent().getSize().width!=0){
	            if (g instanceof VText){
	                newAlt = ((VText)g).getBounds(camera.getIndex()).x * camera.focal / view.getPanel().getComponent().getSize().width - camera.focal;
	            }
	            else if (g instanceof RectangularShape){
	                newAlt = ((RectangularShape)g).getWidth() * camera.focal / view.getPanel().getComponent().getSize().width - camera.focal;
	            }
	            else {
	                newAlt = g.getSize() * camera.focal / view.getPanel().getComponent().getSize().width - camera.focal;
	            }
	        }
	        // compute the new altitude to see glyph g entirely vertically, take max of vertical and horizontal
	        if (view.getPanel().getComponent().getSize().height!=0){
	            double tmpAlt;
	            if (g instanceof VText){
	                tmpAlt = ((VText)g).getBounds(camera.getIndex()).y * camera.focal / view.getPanel().getComponent().getSize().height - camera.focal;
	            }
	            else if (g instanceof RectangularShape){
	                tmpAlt = ((RectangularShape)g).getHeight() * camera.focal / view.getPanel().getComponent().getSize().height - camera.focal;
	            }
	            else {
	                tmpAlt = g.getSize() * camera.focal / view.getPanel().getComponent().getSize().height - camera.focal;
	            }
	            if (tmpAlt > newAlt){newAlt = tmpAlt;}
	        }
	        newAlt *= mFactor;
	        return new SerializableLocation(x, y, newAlt);
	
	}

}
